package ru.spbsu.electromenu.storage.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import ru.spbsu.electromenu.model.Session;
import ru.spbsu.electromenu.storage.SessionStorage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Date: 3/22/11
 * Time: 1:04 AM
 *
 * @author Artem Titov
 */
public class SessionDbStorage extends AbstractDbStorage implements SessionStorage {
    private static final Logger logger = LoggerFactory.getLogger(SessionDbStorage.class);

    private final RowMapper<Session> SESSION_ROW_MAPPER = new RowMapper<Session>() {
        @Override
        public Session mapRow(ResultSet rs, int i) throws SQLException {
            final Session session = new Session();
            session.setId(rs.getInt("Id"));
            session.setTableId(rs.getInt("TableId"));
            return session;
        }
    };

    @Override
    public Session get(int id) {
        return jdbcTemplate.queryForObject("select * from `Session` where `Id`=?", SESSION_ROW_MAPPER, id);
    }

    @Override
    public int put(final Session session) {
        return transactionTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus transactionStatus) {
                logger.debug("Adding session for table {}", session.getTableId());
                final int affectedRows = jdbcTemplate.update("insert into `Session`(`TableId`) values (?)", session.getTableId());
                logger.debug("Session added to database. Retrieving session id.");
                session.setId(jdbcTemplate.queryForInt("select last_insert_id()"));
                logger.debug("Retrieved id: {}", session.getId());
                return affectedRows;
            }
        });
    }

    @Override
    public int update(Session session) {
        return jdbcTemplate.update("update `Session` set `TableId`=? where `Id`=?", session.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from `Session` where `Id`=?", id);
    }

    @Override
    public List<Session> getALl() {
        return jdbcTemplate.query("select * from `Session`", SESSION_ROW_MAPPER);
    }
}
